<template>
  <div :class="{'mobile-create': showMobilePage}" class="select-container-box">
    <el-row class="user-form">
      <el-form ref="editForm" :model="editUserForm" :label-align="showMobilePage?'left':'right'" class="edit-user" label-width="110px">
        <div class="form-box">
          <Title :title="title" class="mb-16"/>
          <el-form-item label="操作员选取" prop="userName" class="is-required form-box-item">
            <!-- 选择员工，单选 -->
            <el-select
              v-loadmore="userLoadMore"
              v-if="type === 'single'"
              v-model="editUserForm.userIds"
              :filter-method="filterData"
              :disabled="!!defaultParams.operatorId"
              popper-class="global-select-down"
              filterable
              size="small"
              placeholder="操作员选取"
              class="user-select filterableSelect remoteRequest1">
              <el-option v-if="defaultParams.operatorId" :value="defaultParams.operatorId" :label="`${defaultParams.jobNumber}${defaultParams.operatorName}`"/>
              <el-option
                v-for="item in userList.items"
                :key="item.id"
                :label="`${item.userName}（${item.jobNumber}）`"
                :value="item.id"/>
              <div v-if="userLoading" class="loading-container"><i class="el-icon-loading"/></div>
            </el-select>
            <!-- 选择部门，多选 -->
            <el-cascader
              v-if="type === 'all'"
              v-model="userIds"
              :options="deptList"
              :props="props"
              :show-all-levels="false"
              filterable
              collapse-tags
              clearable />
          </el-form-item>
          <el-form-item label="操作员状态" prop="status" class="is-required form-box-item">
            <el-switch
              v-model="editUserForm.status"
              :active-value="1"
              :inactive-value="0"/>
          </el-form-item>
          <el-form-item label="所属角色" prop="userName" class="form-box-item">
            <el-select
              v-select-scroll
              v-loadmore="roleLoadMore"
              v-model="editUserForm.role"
              :clearable="isclearable"
              :filter-method="filterRoleData"
              size="small"
              filterable
              placeholder="角色选取"
              multiple
              class="role-select remoteRequest2"
              popper-class="auth-select-role-popper global-select-down"
              value-key="roleId"
              @remove-tag="removeRole"
              @change="roleChange">
              <template v-if="defaultParams || defaultParams.role" >
                <el-option
                  v-for="item in defaultParams.role"
                  :key="item.roleId + 'default'"
                  :value="item"
                  :label="`${item.roleName}${item.status === 0?'[已禁用]':''}`"
                  style="display:none;"/>
              </template>
              <el-option
                v-for="item in roleList.items"
                :key="item.roleId"
                :disabled="!isAdmin && !roleListId.includes(item.roleId)"
                :label="`${item.roleName}${item.status === 0?'[已禁用]':''}`"
                :value="item"/>
              <div v-if="roleLoading" class="loading-container"><i class="el-icon-loading"/></div>
            </el-select>
          </el-form-item>
          <el-form-item v-if="type==='all'" label="设置方式" prop="settingType" class="form-box-item">
            <el-select
              v-model="editUserForm.settingType"
              size="small"
              placeholder="请选择设置方式"
              popper-class="global-select-down">
              <el-option
                v-for="item in settingTypeOptions"
                :key="item.id"
                :label="item.label"
                :value="item.id"/>
            </el-select>
          </el-form-item>
          <el-form-item label="可用权限" prop="status" class="mobile-item-flex">
            <div class="select-auth-list">
              <div class="select-auth-item">
                <div class="auth-title">所属角色权限：</div>
                <selectAuth
                  ref="role-auth-show"
                  :is-disabled="true"
                  :default-auth="defaultParams.roleAuth"
                  tree-id="roleAuth"
                  @nodeExpendChange="nodeExpendChange" />
              </div>
              <div v-if="type !== 'all'" class="select-auth-item">
                <div class="auth-title">个人权限：</div>
                <selectAuth
                  ref="select-auth"
                  :default-auth="editUserForm.auth"
                  show-expend-all
                  class="select-auth-item"
                  tree-id="selectAuth"
                  @nodeExpendChange="nodeExpendChange"
                  @changeAuth="changeAuth"/>
              </div>
            </div>
          </el-form-item>
        </div>
      </el-form>
    </el-row>
    <fixed-pagination>
      <div class="center">
        <el-button :loading="loading" type="primary" size="small" @click="toSave()">保存并返回</el-button>
        <el-button v-if="type !== 'all'" :loading="loading" type="primary" size="small" @click="toSave(true)">保存</el-button>
        <el-button type="info" class="cancel-btn-style" size="small" @click="toClear()">返回</el-button>
      </div>
    </fixed-pagination>
  </div>
</template>
<script>
import { hasRouteAuth } from '@/utils/permission';
import selectAuth from '@/components/AuthPage/selectAuth';
import { roleList, createOperator, editOperator, getOperatorDetail, getDefaultPermission } from '@/api/auth';
import { getList } from '@/api/user';
import { allDeptlist } from '@/api/select';
import { mapState } from 'vuex';
import Title from '@/components/Title';
import ElMessage from '@/utils/message';
import mobileCreate from '@/mixins/mobileCreate';
export default {
  components: { selectAuth, Title },
  mixins: [mobileCreate],
  data() {
    return {
      editUserForm: {
        userIds: '',
        role: [],
        auth: [],
        status: 1,
        settingType: 1
      },
      authDataWord: [],
      defaultParams: {},
      title: '创建角色',
      loading: false,
      type: 'single',
      userList: {},
      userLoading: false,
      roleList: {},
      roleLoading: false,
      deptList: [],
      settingTypeOptions: [
        { id: 1, label: '原有基础新增所选角色' },
        { id: 2, label: '原有基础移除所选角色' },
        { id: 3, label: '所选角色覆盖原有角色' }
      ],
      filterUserName: '',
      filterRoleName: '',
      props: {
        multiple: true,
        value: 'value',
        label: 'label',
        emitPath: false
      },
      userIds: []
    };
  },
  computed: {
    ...mapState({
      'userInfo': state => state.user.userInfo
    }),
    isAdmin() {
      return this.userInfo.userName === '管理员' || hasRouteAuth('auth:operator:adminEdit');
    },
    roleListId() {
      return this.userInfo.roleList.map(i => i.roleId);
    },
    isclearable() {
      if (!this.isAdmin && this.editUserForm.role && this.editUserForm.role.length > 0) {
        const a = this.editUserForm.role.every(i => {
          return this.roleListId.includes(i.roleId);
        });
        return a;
      }
      return true;
    }
  },
  created() {
    const operatorId = this.$route.params.operatorId;
    this.type = this.$route.query.type || 'single';
    if (operatorId) {
      this.title = '编辑操作员';
      this.operatorId = operatorId;
      this.type = 'single';

      this.getDetailData(operatorId);
    } else {
      this.defaultParams = {};
      this.title = '创建操作员';
      this.queryDefaultPermission();
    }
    if (this.type === 'single') {
      this.getUser(1);
    }
    if (this.type === 'all') {
      this.getDeptList();
      this.title = '批量创建操作员';
    }
    this.getRole(1);
    window.removeReadOnly();
  },
  mounted() {
    window.remoteRequest('.remoteRequest1', this.filterData);
    window.remoteRequest('.remoteRequest2', this.filterRoleData);
  },
  methods: {
    async getDetailData(operatorId) {
      try {
        const result = await getOperatorDetail({ id: operatorId });
        if (result.code === 200 && result.data) {
          const defaultParams = result.data;
          this.editUserForm.userIds = Number(operatorId);
          if (defaultParams.role.length > 0) {
            let roleAuth = [];
            this.editUserForm.role = defaultParams.role;
            defaultParams.role.forEach((item, index) => {
              item.$index = index;
              if (item.status === 1) {
                roleAuth = roleAuth.concat(this.jsonParse(item.auth));
              }
            });
            defaultParams.roleAuth = roleAuth;
            if (this.$refs['role-auth-show'] && roleAuth.length > 0) {
              this.$refs['role-auth-show'].setDefault(roleAuth);
            }
          }
          this.editUserForm.auth = defaultParams.auth;
          if (this.$refs['select-auth']) this.$refs['select-auth'].setDefault(defaultParams.auth);
          this.editUserForm.status = defaultParams.status;
          this.defaultParams = defaultParams;
        }
      } catch (error) {
        console.log(error);
      }
    },
    // 获取默认角色
    queryDefaultPermission() {
      getDefaultPermission().then(res => {
        if (res.code === 200) {
          const defaultParams = res.data;
          if (defaultParams.role.length > 0) {
            let roleAuth = [];
            this.editUserForm.role = defaultParams.role;
            defaultParams.role.forEach((item, index) => {
              item.$index = index;
              if (item.status === 1) {
                roleAuth = roleAuth.concat(this.jsonParse(item.auth));
              }
            });
            defaultParams.roleAuth = roleAuth;
            if (this.$refs['role-auth-show'] && roleAuth.length > 0) {
              this.$refs['role-auth-show'].setDefault(roleAuth);
            }
          }
          Object.assign(this.defaultParams, defaultParams);
        }
      });
    },
    changeAuth({ authDataID, authDataWord }) {
      this.editUserForm.auth = authDataID;
      this.authDataWord = authDataWord;
    },
    toSave(isNotBack = false) {
      const editForm = JSON.parse(JSON.stringify(this.editUserForm));
      if (this.userIds.length > 0) {
        editForm.userIds = this.userIds.join();
      }
      if (editForm.userIds === '' || editForm.userIds.length === 0) {
        ElMessage.warning('请选择操作员');
        return;
      }
      if (editForm.role.length === 0 && editForm.auth.length === 0) {
        ElMessage.warning('请选择角色或者可选权限');
        return;
      }
      const mutexMedium = this.authDataWord.filter(i => i.indexOf('medium:medium:') >= 0);
      const mutexSale = this.authDataWord.filter(i => i.indexOf('medium:sale:') >= 0);
      if (mutexMedium.length > 0 && mutexSale.length > 0) {
        ElMessage.warning('媒介管理：销售与执行的订单展示权限只能二选一！');
        return;
      }

      const params = {
        status: editForm.status
      };
      // 判断是选择个人或者部门
      if (typeof editForm.userIds !== 'object') {
        params.userIds = editForm.userIds;
      } else {
        params.userIds = editForm.userIds.join(',');
      }
      // 判断是选择角色或者可用权限
      if (editForm.auth !== '' && editForm.auth.length > 0) {
        params.authIds = editForm.auth.join(',');
      }
      if (editForm.role && editForm.role.length) {
        params.roleIds = editForm.role.map(i => (i.roleId)).join(',');
      }
      if (this.operatorId) {
        params.operatorId = this.operatorId;
        this.editData(params, isNotBack);
      } else {
        if (this.type === 'all') {
          params.settingType = editForm.settingType;
        }
        this.createData(params, isNotBack);
      }
    },
    async editData(params, isNotBack = false) {
      try {
        this.loading = true;
        const res = await editOperator(params);
        this.loading = false;
        if (res.code === 200) {
          ElMessage.success('修改成功');
          if (!isNotBack) {
            localStorage.setItem('resetOperator', '1');
            this.toClear();
          }
          this.$store.dispatch('GetInfo');
        }
      } catch (error) {
        this.loading = false;
      }
    },
    async createData(params, isNotBack = false) {
      try {
        this.loading = true;
        params.isBatch = this.type === 'all' ? 1 : 0;
        const res = await createOperator(params);
        this.loading = false;
        if (res.code === 200) {
          ElMessage.success('配置成功');
          if (!params.isBatch && isNotBack) {
            this.title = '编辑操作员';
            this.operatorId = params.userIds;
            this.type = 'single';
            this.$router.push({
              name: 'editOperator',
              params: { operatorId: params.userIds }
            });
          } else {
            this.toClear();
          }
        }
      } catch (error) {
        this.loading = false;
      }
    },
    toClear() {
      this.$router.push({
        name: 'operatorManage'
      });
    },
    filterData(val) {
      this.filterUserName = val;
      this.getUser(1);
    },
    filterRoleData(val) {
      this.filterRoleName = val;
      this.getRole(1);
    },
    roleChange(value) {
      let roleAuth = [];
      value.forEach((item, index) => {
        item.$index = index; // 记录位置
        if (item.status === 1) {
          roleAuth = roleAuth.concat(this.jsonParse(item.auth));
        }
      });
      if (this.$refs['role-auth-show']) {
        this.$refs['role-auth-show'].setCheckAuth(roleAuth);
      }
    },
    removeRole(value, index) {
      if (value && !this.isAdmin) {
        const rolelist = this.userInfo.roleList.map(i => i.roleId);
        if (!rolelist.includes(value.roleId)) {
          if (value.$index || value.$index === 0) {
            this.editUserForm.role.splice(value.$index, 0, value); // 插入到原位置
          } else {
            this.editUserForm.role.push(value);
          }
          this.roleChange(this.editUserForm.role);
          ElMessage.warning('权限不足，无法删除该角色');
        }
      }
    },
    // 控制两颗树联动
    nodeExpendChange({ key, type, expanded, treeId }) {
      if (type === 'all') {
        this.$refs['role-auth-show'].expandTree(false);
      } else {
        if (treeId === 'selectAuth') {
          if (this.$refs['role-auth-show']) this.$refs['role-auth-show'].expandTreeItem({ key, expanded });
        } else {
          if (this.$refs['select-auth']) this.$refs['select-auth'].expandTreeItem({ key, expanded });
        }
      }
    },
    // 获取数据
    userLoadMore() {
      const userList = this.userList;
      const currentPage = userList.page;
      const isMax = userList.items.length >= userList.total;
      if (!isMax && !this.userLoading) {
        this.getUser(currentPage + 1);
      }
    },
    roleLoadMore() {
      const roleListData = this.roleList;
      const currentPage = roleListData.page;
      const isMax = roleListData.items.length >= roleListData.total;
      if (!isMax && !this.roleLoading) {
        this.getRole(currentPage + 1);
      }
    },
    getUser(page = 1) {
      this.userLoading = true;
      getList(page, 15, { userName: this.filterUserName }).then(({ data }) => {
        this.userLoading = false;
        if (page > 1 && this.userList.items) {
          const concatList = this.userList.items.concat(data.items);
          data.items = concatList;
          this.userList = data;
        } else {
          this.userList = data;
        }
      });
    },
    getRole(page = 1) {
      this.roleLoading = true;
      roleList(page, 10, { status: '', roleName: this.filterRoleName }).then(({ data }) => {
        this.roleLoading = false;
        if (page > 1 && this.roleList.items) {
          const concatList = this.roleList.items.concat(data.items);
          data.items = concatList;
          this.roleList = data;
        } else {
          this.roleList = data;
        }
      });
    },
    getDeptList() {
      allDeptlist().then(res => {
        res.data.forEach(i => { i.disabled = false; });
        this.deptList = res.data;
        this.forEachDept(this.deptList);
      }, result => {});
    },
    forEachDept(tree) {
      for (let i = 0; i < tree.length; i++) {
        if (tree[i].isDepartment) {
          tree[i].value = tree[i].departmentId;
          tree[i].label = tree[i].departmentName;
        } else if (!tree[i].isDepartment) {
          tree[i].value = tree[i].userId;
          tree[i].label = tree[i].userName;
        }
        if (tree[i].children && tree[i].children.length) {
          this.forEachDept(tree[i].children);
        }
      }
    },
    setDisabled(depId) {
      const deptListData = this.deptList;
      deptListData.forEach(item => {
        if (item.id === Number(depId)) {
          item.disabled = true;
          item.leaf = true;
        }
      });
    },
    jsonParse(data) {
      if (!data) return [];
      try {
        return typeof data === 'string' ? JSON.parse(data) : data;
      } catch (error) {
        return data;
      }
    }
  }
};
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
.select-container-box {
    margin: 16px;
    background-color: #fff;
    padding: 24px;
    min-height: calc(100vh - 80px);
    .edit-user {
      .form-box {
        & ::v-deep {
          .el-form-item__label {
            margin-left: 0 !important;
          }
          .form-box-item {
            display: flex;
            align-items: center;
            .el-form-item__content {
              margin-left: 0 !important;
              width:320px;
              .el-input__inner{
                min-width: 320px;
                background:rgba(255,255,255,1);
                border-radius:2px;
                border:1px solid rgba(221,221,221,1);
              }
              .el-input__suffix {
                display: flex;
                align-items: center;
              }
            }
          }

        }
        .form-box-item {
          & ::v-deep {
            .el-form-item {
              margin-bottom: 20px !important;
              .el-input, .el-input__inner {
                width: 320px;
                height: 32px !important;
              }
              .textValue, .el-checkbox {
                margin-left: 10px;
              }
              .el-checkbox__input.is-checked .el-checkbox__inner {
                background-color: #515151;
                border-color: #515151;
              }
              .el-checkbox__input.is-checked + .el-checkbox__label {
                color: #515151;
              }
              .el-checkbox__inner {
                border-color: #515151;
              }
              .el-select__caret.el-input__icon.el-icon-arrow-up {
                line-height: 32px;
              }
            }
          }
        }
        .dept-form {
          margin-bottom: 0 !important;
        }
        .add-btn {
          button {
            width: 740px;
            background-color: #f4f4f4;
            border: 1px dashed #e0e0e0;
            color: #777;
            .add-img {
              margin-right: 8px;
            }
          }
        }
      }
      .crm-add-btn {
        & ::v-deep {
          .el-form-item__content {
            margin-left: 0 !important;
          }
        }
      }
    }
  & ::v-deep {
    .el-tag.el-tag--info {
      // color: #909399 !important;
      color: #406EFF !important;
      background-color: #ecf1ff !important;
    }
    .el-cascader {
      input {
        min-height: 30px;
      }
    }
    .el-scrollbar__wrap {
      height: 300px !important;
    }
  }
}
.loading-container {
  width: 100%;
  text-align: center;
  i {
    color: #999;
  }
}
.auth-title {
  font-size: 14px;
  color: #606266;
}
.select-auth-list {
  display: flex;
  .select-auth-item {
    flex: 1;
  }
}
.auth-select-role-popper {
  .el-select-dropdown__item.selected  {
    &.is-disabled {
      opacity: .5;
    }
  }
}
.mobile-create {
  ::v-deep .el-form-item__label {
    text-align: left;
  }
  .mobile-item-flex {
    display: flex;
    flex-wrap: wrap;
    ::v-deep {
      .el-form-item__label {
        width: 100% !important;
      }
      .el-form-item__content {
        margin-left: 0 !important;
      }
      .select-auth-list {
        flex-wrap: wrap;
        .select-auth-item {
          width: 100%;
          flex: unset !important;
          .expend-all-btn {
            left: unset !important;
            right: 0;
            top: -25px !important;
          }
        }
      }
    }
  }
}
</style>
<style lang="scss">
.el-cascader-panel {
.el-scrollbar__wrap {
  height: 300px !important;
}
}

</style>
